﻿using System;
using System.Drawing;
using RestSharp;

namespace SnapDesktop.ImgurApi
{
    public class Uploader
    {
        public Uploader(string clientId)
        {
            _clientId = clientId;
        }
        const string BaseUrl = "https://api.imgur.com/3/image";

        private readonly string _clientId;



        public T Execute<T>(RestRequest request) where T : new()
        {
            var client = new RestClient {BaseUrl = BaseUrl};
            request.AddHeader("Authorization", "Client-ID " + _clientId);
            request.Method = Method.POST;
            var response = client.Execute<T>(request);

            if (response.ErrorException != null)
            {
                const string message = "Error retrieving response.  Check inner details for more info.";
                var snapDesktopException = new ApplicationException(message, response.ErrorException);
                throw snapDesktopException;
            }
            return response.Data;
        }

        public ImageUploadDataModel Upload(Image i)
        {
            string imageBase64;
            using (var m = new System.IO.MemoryStream()) {
                i.Save(m, System.Drawing.Imaging.ImageFormat.Jpeg);
                imageBase64 = Convert.ToBase64String(m.ToArray());
            }

            var request = new RestRequest();

            request.AddParameter("image", imageBase64);

            return Execute<ImageUploadDataModel>(request);
        }
    }
}